import * as types from '../mutation-types';
import { typeOf } from 'common/js/utils';
// utils
import { findDeeply } from 'common/js/utils';

// basic字典信息
const BASIC = {
    unit: {
        name: '产品单位',
        type: 'product_unit',
        id: 46
    },
    source: {
        name: '产品来源',
        type: 'product_source',
        id: 50
    },
    saleState: {
        name: '产品状态上架',
        type: 'product_status',
        id: 43
    },
    filetype: {
        name: '附件类别',
        type: 'filetype',
        id: 31
    },
    region: {
        name: '所属区域',
        type: 'region',
        id: 126
    },
    customerSource: {
        name: '客户来源',
        type: 'customer_source',
        id: 134
    },
    customerTag: {
        name: '客户标签',
        type: 'customer_tag',
        id: 105
    },
    customerIndustry: {
        name: '所属行业',
        type: 'customer_industry',
        id: 4
    },
    customerCostType: {
        name: '报销项',
        type: 'customer_cost_type',
        id: 108
    }
}

export const setTopTypeAndProductTree = ({ commit }, tree = []) => {
  if (typeOf(tree) !== 'array') throw new Error('dictTree类型不对');
  commit(types.SET_PRODUCT_TREE, tree);
  const topTypeList = tree.map(item => ({
    fatherid: item.fatherid,
    id: item.id,
    type_name: item.type_name,
    type_no: item.type_no
  }));
  commit(types.SET_TOP_TYPE, topTypeList);
};

/**
 * 设置 dictTree 以及相关 state
 * @param commit
 * @param tree
 */
export const setDictTree = ({ commit }, tree = []) => {
  if (typeOf(tree) !== 'array') throw new Error('dictTree类型不对');
  // 设置字典树state
  commit(types.SET_DICT_TREE, tree);
  // 设置产品单位state
  commit(types.SET_UNIT, _getOriginalInfo('unit', tree));
  // 设置产品来源state
  commit(types.SET_SOURCE, _getOriginalInfo('source', tree));
  // 设置产品状态上架state
  commit(types.SET_SALESTATE, _getOriginalInfo('saleState', tree));
  // 设置附件类别state
  commit(types.SET_FILETYPE, _getOriginalInfo('filetype', tree));
  // 设置所属区域state
  commit(types.SET_REGION, _getOriginalInfo('region', tree));
  // 设置客户来源state
  commit(types.SET_CUSTOMER_SOURCE, _getOriginalInfo('customerSource', tree));
  // 设置客户标签state
  commit(types.SET_CUSTOMER_TAG, _getOriginalInfo('customerTag', tree));
  // 设置所属行业state
  commit(types.SET_CUSTOMER_INDUSTRY, _getOriginalInfo('customerIndustry', tree));
  // 设置报销项state
  commit(types.SET_CUSTOMER_COST_TYPE, _getOriginalInfo('customerCostType', tree));
};

/**
 * 将各种字典字段的具体数据从 dictTree 中抽离出来
 * @param field
 * @param data
 * @private
 */
function _getOriginalInfo(field, data) {
  let fatherData = findDeeply(data, item => item.type === BASIC[field].type) || [],
      list = fatherData.children;
  return list;
}